package com.unittec.drainage.provider.utils;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * 字符串加密解密工具 对称加密
 *
 * @author JiKun.Li
 * @date 2017-11-16.
 * @Email: tracenet@126.com
 */
public class TokenDescUtils {

    /**
     * 加密数据令牌
     *
     * @param input 输入数据
     * @return 加密后的结果
     */
    public static String encrypt(String input) throws Exception {
        byte[] keyiv = {15, 26, 37, 41, 50, 62, 73, 83};
        String enc = "UTF-8";
        DESedeKeySpec spec = new DESedeKeySpec(new BASE64Decoder().decodeBuffer("6wSjRnjreHUcRwtO99o6ZEPd7C5ow0SB"));
        Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding");
        IvParameterSpec ips = new IvParameterSpec(keyiv);
        cipher.init(Cipher.ENCRYPT_MODE, SecretKeyFactory.getInstance("desede").generateSecret(spec), ips);
        byte[] bOut = cipher.doFinal(input.getBytes(enc));
        return URLEncoder.encode(new BASE64Encoder().encode(bOut), enc);
    }

    /**
     * 解密数据令牌
     *
     * @param input 加密的令牌数据
     * @return 解密后的结果
     */
    public static String decrypt(String input) throws Exception {
        byte[] keyiv = {15, 26, 37, 41, 50, 62, 73, 83};
        String enc = "UTF-8";
        DESedeKeySpec spec = new DESedeKeySpec(new BASE64Decoder().decodeBuffer("6wSjRnjreHUcRwtO99o6ZEPd7C5ow0SB"));
        SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("desede");
        Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding");
        IvParameterSpec ips = new IvParameterSpec(keyiv);
        cipher.init(Cipher.DECRYPT_MODE, secretKeyFactory.generateSecret(spec), ips);
        byte[] bOut = cipher.doFinal(new BASE64Decoder().decodeBuffer(URLDecoder.decode(input, enc)));
        return new String(bOut, enc);
    }
}
